/**
 * 
 */
package com.etrans.web.gps.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.common.Constant;

/**
 * <p>Title: CheckLoginFilter.java<／p>
 * <p>Description: <／p>
 * <p>Copyright: Copyright (c) 2007<／p>
 * <p>Company: E-trans<／p>
 * 
 * @author R.Lao
 * @date 2017年6月15日
 * @time 上午9:46:21
 * @version 1.0
 */
public class CheckLoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest _request, ServletResponse _response,
			FilterChain filterChain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) _request;
        HttpServletResponse response = (HttpServletResponse) _response;
        SysUser user = (SysUser)request.getSession().getAttribute(Constant.LOGIN_SESSION_NAME);
        
        // 获得用户请求的URI
        String contextPath = request.getRequestURI();
        if(contextPath.contains("login.html") || contextPath.contains("vehicleShareOverdue.jsp")
        		|| contextPath.contains("loginOut.html") || contextPath.contains("subScribe.html")
        		|| (contextPath.contains("doLogin.html") && request.getMethod().equalsIgnoreCase("post"))|| contextPath.contains("shareVehicle.html")

        ){
        	filterChain.doFilter(_request, _response);
            return;
//			直接跳dologin时 调回login.HTML
		}else if (contextPath.contains("doLogin.html") && !request.getMethod().equalsIgnoreCase("post")){
			response.sendRedirect(request.getContextPath()+"/login.html");
			return;
        }else{
        	 if (user == null) {
        		 if (request.getHeader("x-requested-with") != null 
        				 && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")
        				 ){ 
        			 //如果是ajax请求响应头会有，x-requested-with  
     	            response.setHeader("sessionstatus", "timeout");//在响应头设置session状态  
        		 }else if(contextPath.contains(".html")){
        			 response.sendRedirect(request.getContextPath()+"/relogin.html");
        		 }else{//输入域名返回登录页面
        			 filterChain.doFilter(_request, _response);
        		 }
                 return;
             }else {
                 filterChain.doFilter(_request, _response);
                 return;
             }		
        }
	}

	@Override
	public void destroy() {
		
	}

}
